package com.egg.ylt.activity;

import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.egg.ylt.R;
import com.egg.ylt.SQLiteUtil.RecordsDao;
import com.egg.ylt.Utils.Constants;
import com.egg.ylt.Utils.CustomUtils;
import com.egg.ylt.Utils.DividerItemDecoration;
import com.egg.ylt.Utils.StatusBarUtil;
import com.egg.ylt.adapter.ADA_ConsultRecyclerView;
import com.egg.ylt.adapter.ADA_SearchHeat;
import com.egg.ylt.adapter.ADA_SearchHistory;
import com.egg.ylt.pojo.HeatTitleEntity;
import com.egg.ylt.pojo.HomePageEntity;
import com.egg.ylt.presenter.impl.SearchNewsPresenterImpl;
import com.egg.ylt.view.ISearchNewsView;
import com.yonyou.framework.library.base.BaseActivity;
import com.yonyou.framework.library.bean.ErrorBean;
import com.yonyou.framework.library.common.utils.AppSharedPreferences;
import com.yonyou.framework.library.common.utils.ListUtil;
import com.yonyou.framework.library.common.utils.ToastUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class ACT_SearchNews extends BaseActivity<SearchNewsPresenterImpl> implements ISearchNewsView {


    @BindView(R.id.edit_keyword_search)
    EditText editKeywordSearch;
    @BindView(R.id.iv_delete_search)
    ImageView ivDeleteSearch;
    @BindView(R.id.btn_cancel_search)
    TextView btnCancelSearch;
    @BindView(R.id.ll_top_search)
    LinearLayout llTopSearch;
    @BindView(R.id.list_history)
    RecyclerView listHistory;
    @BindView(R.id.list_you_think)
    RecyclerView listYouThink;
    @BindView(R.id.list_search_news)
    RecyclerView listSearchNews;
    @BindView(R.id.target_view_ll)
    LinearLayout llTargetView;
    @BindView(R.id.ll_history)
    LinearLayout llHistory;
    @BindView(R.id.ll_heat)
    LinearLayout llHeat;
    @BindView(R.id.top_ll_hide)
    LinearLayout topLlHide;

    private String pageSize = "20";
    private int pageNum = 1;

    private AppSharedPreferences mSp;
    private ADA_SearchHeat ada_searchHeat;
    private ADA_ConsultRecyclerView mNewsAdapter;
    private RecordsDao recordsDao;
    private List<String> searchRecordsList;
    private List<String> tempList;
    private ADA_SearchHistory historyAdapter;

    @Override
    protected void getBundleExtras(Bundle extras) {

    }

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.act_search_news;
    }

    @Override
    protected View getLoadingTargetView() {
        return llTargetView;
    }

    @Override
    protected void initViewsAndEvents() {

        StatusBarUtil.setStatusBarColor(this, R.color.color_f3f3f3);
        StatusBarUtil.StatusBarLightMode(this);
        CustomUtils.setImmersiveStatusBar(mContext, llTopSearch);
        mSp = new AppSharedPreferences(mContext);

        //初始化view
        initView();

    }

    private void initView() {
        //历史记录listview
        setHistory();

        //热度listview
        setHeat();

        //设置咨询别表list
        setNews();

        //保存搜索记录到数据库
        initListener();

    }

    private void setNews() {
        //设置布局管理器
        LinearLayoutManager mLinearLayoutManager1 = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        };
        listSearchNews.setLayoutManager(mLinearLayoutManager1);
        //设置适配器
        mNewsAdapter = new ADA_ConsultRecyclerView(mContext);
        listSearchNews.setAdapter(mNewsAdapter);

        mNewsAdapter.setOnItemClickListener(new ADA_ConsultRecyclerView.OnItemClickListener() {
            @Override
            public void onItemClick(String id, String type) {
                Bundle mBundle = new Bundle();
                mBundle.putString("id", id);
                switch (type) {
                    case "0":
                    case "1":
                    case "2":
                        readyGo(ACT_NewsDetails.class, mBundle);
                        break;
                    case "3":
                        readyGo(ACT_VideoPlaying.class, mBundle);
                        break;
                }
            }
        });

    }

    private void setHeat() {
        //设置布局管理器
        GridLayoutManager mLinearLayoutManager1 = new GridLayoutManager(mContext, 2) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        };

        listYouThink.setLayoutManager(mLinearLayoutManager1);
        //设置间距
        listYouThink.addItemDecoration(new DividerItemDecoration(mContext, 2));
        //设置适配器
        ada_searchHeat = new ADA_SearchHeat(mContext);
        listYouThink.setAdapter(ada_searchHeat);
        //item监听
        ada_searchHeat.setOnItemClickListener(new ADA_SearchHeat.OnItemClickListener() {
            @Override
            public void onClick(String id) {
                //判断数据库中是否存在该记录
                if (!recordsDao.isHasRecord(id)) {
                    tempList.add(id);
                }
                //将搜索记录保存至数据库中
                recordsDao.addRecords(id);
                //获取数据并颠倒历史数据
                reversedList();
                //设置数据
                historyAdapter.setmList(searchRecordsList);
                editKeywordSearch.setText(id);
                mPresenter.getVague(Constants.TOKEN, id, pageSize, String.valueOf(pageNum), Constants.COMPANYID);
            }
        });

        //请求热度词汇
        mPresenter.getHeat(Constants.TOKEN);
    }

    private void setHistory() {
        recordsDao = new RecordsDao(mContext);
        searchRecordsList = new ArrayList<>();
        tempList = new ArrayList<>();

        //获取数据并颠倒历史数据
        reversedList();
        //设置布局管理器
        GridLayoutManager mLinearLayoutManager = new GridLayoutManager(mContext, 2) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        };
        listHistory.setLayoutManager(mLinearLayoutManager);
        //设置间距
        listHistory.addItemDecoration(new DividerItemDecoration(mContext, 2));
        //设置适配器
        historyAdapter = new ADA_SearchHistory(mContext);
        listHistory.setAdapter(historyAdapter);
        //设置数据
        historyAdapter.setmList(searchRecordsList);

        //条目监听
        historyAdapter.setOnItemClickListener(new ADA_SearchHistory.OnItemClickListener() {
            @Override
            public void onClick(String id) {
                editKeywordSearch.setText(id);
                mPresenter.getVague(Constants.TOKEN, id, pageSize, String.valueOf(pageNum), Constants.COMPANYID);
            }
        });
    }

    private void initListener() {

        editKeywordSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    if (editKeywordSearch.getText().toString().length() > 0) {

                        String record = editKeywordSearch.getText().toString();

                        //判断数据库中是否存在该记录
                        if (!recordsDao.isHasRecord(record)) {
                            tempList.add(record);
                        }
                        //将搜索记录保存至数据库中
                        recordsDao.addRecords(record);
                        reversedList();

                        //根据关键词去搜索
                        mPresenter.getVague(Constants.TOKEN, record, pageSize, String.valueOf(pageNum),
                                Constants.COMPANYID);
                    } else {
                        ToastUtil.makeText(mContext, "搜索内容不能为空", false);
                    }
                }
                return false;
            }
        });

        //历史记录点击事件

    }

    @Override
    protected boolean isApplyStatusBarTranslucency() {
        return false;
    }

    @Override
    protected boolean isBindEventBusHere() {
        return false;
    }

    @Override
    protected boolean toggleOverridePendingTransition() {
        return false;
    }

    @Override
    protected TransitionMode getOverridePendingTransitionMode() {
        return null;
    }

    @Override
    protected boolean isApplyKitKatTranslucency() {
        return false;
    }

    @Override
    public void showBusinessError(ErrorBean error) {

    }

    @Override
    public void getVagueData(HomePageEntity entity) {
        //根据关键词查询到的信息
        if (ListUtil.isListEmpty(entity.getList())) {
            topLlHide.setVisibility(View.VISIBLE);
            listSearchNews.setVisibility(View.GONE);
            ToastUtil.makeText(mContext, "没有搜索到相关资讯", false);
            return;
        }
        //隐藏历史记录
        topLlHide.setVisibility(View.GONE);
        listSearchNews.setVisibility(View.VISIBLE);
        //设置查询到的咨询数据
        mNewsAdapter.addList(entity.getList());
    }

    @Override
    public void getHeatData(HeatTitleEntity entity) {
        //获取关键热度
        if (ListUtil.isListEmpty(entity.getList())) {
            return;
        }
        //推荐的词汇
        ada_searchHeat.setmList(entity.getList());
    }

    @OnClick({R.id.iv_shop_back, R.id.iv_delete_search, R.id.btn_cancel_search, R.id.btn_delete_history})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_shop_back://返回键
                finish();
                break;
            case R.id.iv_delete_search://删除关键字
                editKeywordSearch.setText("");
                break;
            case R.id.btn_cancel_search://取消
                //展示历史记录
                topLlHide.setVisibility(View.VISIBLE);
                // 隐藏咨询页面
                listSearchNews.setVisibility(View.GONE);
                break;
            case R.id.btn_delete_history://清除历史记录
                tempList.clear();
                searchRecordsList.clear();
//                reversedList();
                recordsDao.deleteAllRecords();
                historyAdapter.deleteAllList();
                break;
        }
    }

    //颠倒list顺序，用户输入的信息会从上依次往下显示
    private void reversedList() {
        tempList.clear();
        searchRecordsList.clear();
        tempList.addAll(recordsDao.getRecordsList());
        for (int i = tempList.size() - 1; i >= 0; i--) {
            searchRecordsList.add(tempList.get(i));
        }
    }
}
